<template>
    <el-dialog 
        v-model="isDialogFormVisible" 
        :title="dialogTitle"
        width="600px"
        append-to-body
        :modal="true"
        :lock-scroll="false"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :destroy-on-close="true"
        @close="handleClose"
    >
        <el-form 
            ref="ruleFormRef" 
            :rules="rules" 
            :model="editItem"
            label-width="100px"
        >
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="菜单名称" prop="Label">
                        <el-input 
                            v-model="editItem.Label" 
                            placeholder="请输入菜单名称"
                            clearable
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="路径" prop="Path">
                        <el-input 
                            v-model="editItem.Path" 
                            placeholder="请输入路径，如：/home"
                            clearable
                        />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="父菜单" prop="ParentId">
                        <el-select 
                            v-model="editItem.ParentId" 
                            placeholder="请选择父菜单"
                            style="width: 100%"
                            clearable
                        >
                            <el-option :label="'无（顶级菜单）'" :value="0" />
                            <el-option 
                                v-for="menu in parentMenuOptions" 
                                :key="menu.Id" 
                                :label="menu.Label" 
                                :value="menu.Id" 
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="排序" prop="Order">
                        <el-input-number 
                            v-model="editItem.Order" 
                            :min="0"
                            :max="999"
                            style="width: 100%"
                            placeholder="数字越小越靠前"
                        />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-form-item label="组件路径" prop="Component">
                <el-input 
                    v-model="editItem.Component" 
                    placeholder="不填表示菜单，填写表示页面，如：/src/views/Home.vue"
                    clearable
                />
            </el-form-item>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="显示状态" prop="IsShow">
                        <el-switch v-model="editItem.IsShow" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="菜单布局" prop="IsLayout">
                        <el-switch 
                            v-model="editItem.IsLayout" 
                            active-text="菜单"
                            inactive-text="页面"
                        />
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 动态表单项 -->
            <!-- <template v-for="item in props.bgcolumnNames" :key="item.Name">
                <DynamicFormItem
                    v-if="!isExcludedField(item.Name)"
                    :item="item"
                    :model="editItem"
                    :selectChange="selectChange"
                />
            </template> -->
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose" :icon="Close">取消</el-button>
                <el-button type="primary" @click="onConfirm" :icon="Check" :loading="submitting">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { Check, Close } from '@element-plus/icons-vue';
import JSCodeMirror from '../../components/JSCodeMirror.vue';
import DynamicFormItem from '../../components/DynamicFormItem.vue';
import type { ElForm, FormInstance, FormRules } from 'element-plus';

// 响应式数据
const isDialogFormVisible = ref(false);
const submitting = ref(false);
const ruleFormRef = ref<FormInstance>();

interface EditItemType {
    [key: string]: any;
    Id?: number;
    Label?: string;
    Path?: string;
    Component?: string;
    ParentId?: number;
    Order?: number;
    IsShow?: boolean;
    IsLayout?: boolean;
    CreateTime?: string;
    UpdateTime?: string;
}

const editItem = reactive<EditItemType>({});

// Props
const props = defineProps({
    bgcolumnNames: {
        type: Array as () => any[],
        default: () => []
    },
    parentMenuOptions: {
        type: Array as () => Array<{Id: number, Label: string}>,
        default: () => []
    }
});

// Emits
const emit = defineEmits(['confirm', 'selectChange']);

// 计算属性
const dialogTitle = computed(() => {
    return editItem.Id && editItem.Id > 0 ? '编辑菜单' : '新增菜单';
});

// 表单验证规则
const rules = reactive<FormRules>({
    Label: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' },
        { min: 1, max: 50, message: '菜单名称长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    Path: [
        { required: true, message: '请输入路径', trigger: 'blur' },
        { pattern: /^\/[a-zA-Z0-9\/\-_]+$/, message: '路径格式不正确，应以/开头', trigger: 'blur' }
    ],
    Component: [
        // 组件路径不是必填的，如果不填表示是菜单，如果填了表示是页面
    ],
    ParentId: [
        { required: true, message: '请选择父菜单', trigger: 'change' }
    ],
    Order: [
        { required: true, message: '请输入排序值', trigger: 'blur' },
        { type: 'number', min: 0, max: 999, message: '排序值应在 0-999 之间', trigger: 'blur' }
    ]
});

// 方法
const isExcludedField = (fieldName: string) => {
    const excludedFields = ['Id', 'Label', 'Path', 'Component', 'ParentId', 'Order', 'IsShow', 'IsLayout'];
    return excludedFields.includes(fieldName);
};

const selectChange = (colItem: any) => {
    emit("selectChange", editItem, colItem);
};

// 监听组件路径变化，自动设置菜单布局
watch(() => editItem.Component, (newValue) => {
    // 如果组件路径为空或undefined，设置为菜单（IsLayout = true）
    // 如果组件路径有值，设置为页面（IsLayout = false）
    editItem.IsLayout = !newValue || newValue.trim() === '';
}, { immediate: true });

const open = (item: EditItemType) => {
    // 使用 requestAnimationFrame 延迟显示，避免阻塞UI
    requestAnimationFrame(() => {
        isDialogFormVisible.value = true;
        
        // 直接设置数据，避免复杂的对象操作
        editItem.Id = item.Id || 0;
        editItem.Label = item.Label || '';
        editItem.Path = item.Path || '';
        editItem.Component = item.Component || '';
        editItem.ParentId = item.ParentId || 0;
        editItem.Order = item.Order || 0;
        editItem.IsShow = item.IsShow !== undefined ? item.IsShow : true;
        editItem.IsLayout = item.IsLayout !== undefined ? item.IsLayout : true;
        editItem.CreateTime = item.CreateTime || new Date().toISOString();
        editItem.UpdateTime = item.UpdateTime || null;
    });
};

const handleClose = () => {
    isDialogFormVisible.value = false;
    submitting.value = false;
};

const onConfirm = async () => {
    if (!ruleFormRef.value) return;
    
    try {
        submitting.value = true;
        await ruleFormRef.value.validate();
        emit("confirm", { ...editItem });
    } catch (error) {
        console.error('表单验证失败:', error);
        ElMessage.error('请检查表单填写是否正确');
    } finally {
        submitting.value = false;
    }
};



// 暴露方法
defineExpose({ open, close: handleClose });
</script>

<style scoped>


.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}





:deep(.el-input-number) {
    width: 100%;
}

:deep(.el-select) {
    width: 100%;
}


</style> 